// Timer Run-mode state machine.
// This is part of a bigger state machine and is the entry point for the overall FSM.
//

#include "Bargraph.h"

// Relay On States. (ENTRY S0E0)
//
void s0e0(void)
{
	// Actions
	//
	Set_Rel(1);
	SM_Tim_State = S1_tim_waiting;
}

void s0e1(void)
{
	Set_Rel(1);
	systick = Trigger_Load;
}

void s0e2(void)
{	
}

// Timer Waiting States
//
void s1e0(void)
{
}

void s1e1(void)
{
	SM_Tim_State = S0_rel_on;
}

void s1e2(void)
{
	SM_Tim_State = S2_rel_off;
}

// Relay Off States
//
void s2e0(void)
{
	Set_Rel(0);
	ShiftOut(0);
	SM_Tim_Killsig=1;
}

void s2e1(void)
{
	Set_Rel(0);
	ShiftOut(0);
	SM_Tim_Killsig=1;
}

void s2e2(void)
{
	Set_Rel(0);
	ShiftOut(0);
	SM_Tim_Killsig=1;
}


// State Transition Engine
//
void SM_Tim_Redirect(int br_state,int br_event)
{
	if(systick2 == 80 ) ShiftOut( 0 );
	if(systick2 == 0)
	{
		systick2 = 159;
		ShiftOut( BarGraph(systick, Trigger_Load) );
	}

 	switch(br_state)
	{
	case 0:		// State 0 handler

		if(br_event==0) s0e0();
		if(br_event==1) s0e1();
		if(br_event==2) s0e2();
		break;

	case 1:		// State 1 handler

		if(br_event==0) s1e0();
		if(br_event==1) s1e1();
		if(br_event==2) s1e2();
		break;

	case 2:		// State 1 handler
		if(br_event==0) s2e0();
		if(br_event==1) s2e1();
		if(br_event==2) s2e2();

	}
}

// Entry Point
//
void SM_Tim_main( void )
{
	// Setup initial State machine condition
	//
	// This is effectively the state machines memory
	//
	SM_Tim_State = S0_rel_on;
	SM_Tim_Killsig = 0;

	systick2 = 159;

	// Event driver.
	do
	{
		if( (systick==0) && (SM_Tim_State == S1_tim_waiting) )
			SM_Tim_Event = E2_timeout;
		else
			SM_Tim_Event = TrigState() ? E1_trig : E0_notrig; 

		SM_Tim_Redirect(SM_Tim_State, SM_Tim_Event);
	} while( !SM_Tim_Killsig ); // Keep going until we reach the exit condition.
	ShiftOut(0);
}